package cn.gyouzhe.controller;

import cn.gyouzhe.component.taobao.TaobaoComponent;
import cn.gyouzhe.entity.Category;
import cn.gyouzhe.entity.FeedBack;
import cn.gyouzhe.service.ICacheService;
import cn.gyouzhe.service.ICategoryService;
import cn.gyouzhe.service.IFeedBackService;
import cn.gyouzhe.service.IGoodService;
import cn.gyouzhe.utils.Request;
import cn.gyouzhe.vo.DataResult;
import cn.gyouzhe.vo.GoodVo;
import cn.gyouzhe.vo.PageResult;
import cn.gyouzhe.vo.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * desc
 *
 * @author wangchuan
 * @datetime 2018/2/26 0:32
 */
@Slf4j
@Controller
public class IndexController {
    private static final int PAGESIZE = 80;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IGoodService goodService;
    @Autowired
    private TaobaoComponent taobaoComponent;
    @Autowired
    private IFeedBackService feedBackService;
    @Autowired
    private ICacheService cacheService;

    private static Map<String, String> GOOD_COLUMN_MAP = new HashMap<>();
    /**
     * 电话正则
     */
    private static Pattern PHONE_REGEX = Pattern.compile("^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\\\d{8}$");
    /**
     * QQ正则
     */
    private final static Pattern QQ_REGEX = Pattern.compile("[1-9][0-9]{4,14}");

    static {
        GOOD_COLUMN_MAP.put("1", "nvz");
        GOOD_COLUMN_MAP.put("2", "my");
        GOOD_COLUMN_MAP.put("3", "hzp");
        GOOD_COLUMN_MAP.put("4", "jj");
        GOOD_COLUMN_MAP.put("5", "xbps");
        GOOD_COLUMN_MAP.put("6", "ms");
        GOOD_COLUMN_MAP.put("7", "wtcp");
        GOOD_COLUMN_MAP.put("8", "smjd");
        GOOD_COLUMN_MAP.put("9", "nz");
        GOOD_COLUMN_MAP.put("10", "ny");
        GOOD_COLUMN_MAP.put("nvz", "1");
        GOOD_COLUMN_MAP.put("my", "2");
        GOOD_COLUMN_MAP.put("hzp", "3");
        GOOD_COLUMN_MAP.put("jj", "4");
        GOOD_COLUMN_MAP.put("xbps", "5");
        GOOD_COLUMN_MAP.put("ms", "6");
        GOOD_COLUMN_MAP.put("wtcp", "7");
        GOOD_COLUMN_MAP.put("smjd", "8");
        GOOD_COLUMN_MAP.put("nz", "9");
        GOOD_COLUMN_MAP.put("ny", "10");
    }

    /**
     * 加载商品栏目总数
     * @return 商品栏目总数MAP
     */
    private Map<String, Integer> loadGoodColumnTotal() {
        Map<String, Integer> goodColumnMap = new HashMap<>();
        Map<Integer, Integer> goodColumnCountMap = goodService.selectColumnGoodCount();
        int total = 0;
        for(Integer key : goodColumnCountMap.keySet()) {
            String columnCode = GOOD_COLUMN_MAP.get(String.valueOf(key));
            int columnTotal = goodColumnCountMap.get(key);
            total += columnTotal;
            goodColumnMap.put(columnCode, columnTotal);
        }
        goodColumnMap.put("all", total);
        return goodColumnMap;
    }

    private String currentUrl(String url, String keyword, int type, String sort) {
        StringBuilder urlBuilder = new StringBuilder(url);
        boolean hasQuery = false;
        if(StringUtils.isNotEmpty(keyword)) {
            urlBuilder.append("?").append("kw=" + keyword);
            hasQuery = true;
        }
        if(type > 0) {
            if(!hasQuery) {
                hasQuery = true;
                urlBuilder.append("?");
            } else {
                urlBuilder.append("&");
            }
            urlBuilder.append("type=").append(type);
        }
        if(StringUtils.isNotEmpty(sort) && (StringUtils.equals(sort, "p") || StringUtils.equals(sort, "s"))) {
            urlBuilder.append(hasQuery ? "&" : "?").append("sort=").append(sort);
        }
        return urlBuilder.toString();
    }

    /**
     * 处理意见反馈
     * @return
     */
    @RequestMapping(value = "/feedback", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> feedback(String content, String contact) {
        Map<String, Object> returnMap = new HashMap<>();
        if(PHONE_REGEX.matcher(contact).matches() || QQ_REGEX.matcher(contact).matches()) {
            FeedBack feedBack = new FeedBack();
            feedBack.setContact(contact);
            feedBack.setContent(content);
            feedBack.setCreate(LocalDateTime.now());
            feedBackService.saveFeedback(feedBack);
            returnMap.put("code", 200);
            returnMap.put("msg", "保存意见反馈成功");
        } else {
            returnMap.put("code", 500);
            returnMap.put("msg", "请输入正确的联系方式");
        }

        return returnMap;
    }

    @RequestMapping(value = {"/", "/{pagekey}", "/{pagekey}/{goodColumn}"}, method = RequestMethod.GET)
    public String page(
            @RequestParam(required = false, name = "kw") String keyword,
            @PathVariable(required = false) String pagekey,
            @PathVariable(required = false) String goodColumn,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "0") int type,  //0全部 1天猫  2淘宝
            @RequestParam(required = false, defaultValue = "n") String sort,   //排序 p价格 s销量 n最新
            HttpServletRequest request,
            Model model) {
        if(StringUtils.isEmpty(pagekey))
            pagekey = "index";
        int cid = 0;
        if(StringUtils.isEmpty(goodColumn)) {
            goodColumn = "all";
        }
        cid = NumberUtils.toInt(GOOD_COLUMN_MAP.get(goodColumn), 0);
        List<Category> categorys = categoryService.selectCategory();
        PageResult<GoodVo> pageResult =
                StringUtils.isEmpty(keyword) ?
                        goodService.selectGoodInfo(pagekey, cid, page, PAGESIZE, type, sort) :
                        taobaoComponent.search(keyword, type == 1, StringUtils.equals("p", sort) ? 4 : StringUtils.equals("s", sort) ? 9 : -1, page, PAGESIZE);
        model.addAttribute("result", pageResult);
        model.addAttribute("goodColumnMap", loadGoodColumnTotal());
        model.addAttribute("currentGoodColumn", goodColumn);
        model.addAttribute("categorys", categorys);
        model.addAttribute("pagekey", pagekey);
        model.addAttribute("type", type);
        model.addAttribute("sort", sort);
        model.addAttribute("keyword", StringUtils.isNotEmpty(keyword) ? keyword : "");
        model.addAttribute("haskeyword", StringUtils.isNotEmpty(keyword));
        String currentUrl = currentUrl(request.getRequestURI(), keyword, type, sort);
        model.addAttribute("currentUrl", currentUrl);
        model.addAttribute("currentUri", request.getRequestURI());
        model.addAttribute("haquery", StringUtils.contains(currentUrl, "?"));
        return "index";
    }

    /**
     * 转链商品
     *
     * @param goodId  商品ID
     * @param couponId 券ID
     * @return 转链结果
     */
    @RequestMapping(value = "/good/transform", method = RequestMethod.POST)
    @ResponseBody
    public Result transform(String goodId, String couponId) {
        String key = goodId + couponId;
        Object val = cacheService.getCache(key);
        if(null != val) {
            Map<String, String> data = new HashMap<>();
            data.put("extLink", val.toString());
            return new DataResult<>(data);
        } else {
            String sessionId = "70000100904785461c3c89e9cca93c5f7e8f0b8434b8e59573e2d57b9f425d6079b142a897257852";
            String url = transform(goodId, taobaoComponent.pid(), sessionId);
            if(StringUtils.isNotEmpty(url)) {
                url += "&activityId=" + couponId;
                url = taobaoComponent.spread(url);
                cacheService.addCache(key, url);
                Map<String, String> data = new HashMap<>();
                data.put("extLink", url);
                return new DataResult<>(data);
            }
            return new Result("转链失败");
        }
    }

    /**
     * 转链
     *
     *
     * @param pid   用户PID
     * @param goodId  商品ID
     * @return 转链URL
     */
    private String transform(String goodId, String pid, String sessionId) {
        String requestUrl = "http://api_user.qqku.com/tb/get_gaoyong.php?iid=" + goodId + "&fullpid=" + pid + "&session=" + sessionId;
//        String requestUrl = "http://api.yishoudan.com/newapi/gysq/taobao_user_id/" + userId + "/num_iid/" + goodId + "/pid/" + pid;
        Request.Response response = Request.getInstance().get(requestUrl);
        if(response.getCode() == HttpStatus.SC_OK) {
            JSONObject obj = JSON.parseObject(response.getContent());
            if(obj.containsKey("coupon_click_url")) {
                return obj.getString("coupon_click_url");
            }
        }
        log.error("返回结果为:" + response.getContent());
        return null;
    }
}
